﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Battle
{
    public class FieldPVEBattleOver : IBattleOver
    {
        public BattleType GetBattleType()
        {
            return BattleType.FIELD_PVE;
        }

        bool localResult;
        bool remoteResult;

        OnBattleResult onResult;
        public FieldPVEBattleOver(OnBattleResult onResult)
        {
            this.onResult = onResult;

        }

        public void Excute()
        {
            localResult = BattleManager.Instance.battleViewCtrl.winCamp == BattleCamp.Attacker;
            remoteResult = false;
            AskFieldPVEFightResult();
        }

        void AskFieldPVEFightResult()
        {
            ProtoBuf.Message.CSSidePveFightEnd msg = new ProtoBuf.Message.CSSidePveFightEnd();
            msg.fightId = StaticData.curBattleData.fightId;
            var data = BattleManager.Instance.battleEngine.compute.data;
            StaticData.curBattleData.myCopyBattlePlayer.inst.anger = data.attacker.angerNum;
            foreach (var hero in StaticData.curBattleData.myCopyBattlePlayer.formation)
            {
                var actor = data.GetActorByUID("0_" + hero.guid);
                hero.inst.curHp = actor.attribute.hp;
                hero.pose = actor.MainPosition.ToFPID();
            }
            msg.battlePlayer = StaticData.curBattleData.myCopyBattlePlayer;

            msg.result = localResult ? 1 : 0;
            msg.optRecord = BattleNetOver.ParseOptRecord();

            NetAPI.RegistSocketHandler(ProtoBuf.Message.OpDefine.SCSidePveFightEnd, FieldPVEFightResultHandler);
            NetAPI.SendSocket(ProtoBuf.Message.OpDefine.CSSidePveFightEnd, msg);
        }

        void FieldPVEFightResultHandler(object obj)
        {
            ProtoBuf.Message.SCSidePveFightEnd end = (ProtoBuf.Message.SCSidePveFightEnd)obj;
            StaticData.pveEnd = end;
            remoteResult = end.fightResult == 1;
            StaticData.isLastBattleWin = remoteResult; 
            StaticData.lastBattleEndMsg = end;
            NetAPI.UnregisterSocketHandler(ProtoBuf.Message.OpDefine.SCSidePveFightEnd, FieldPVEFightResultHandler);
            End();

        }

        public void End()
        {
            if (onResult != null)
            {
                onResult(remoteResult);
            }
        }
    }
}
